import numpy as np
from tensorflow.keras.models import load_model
from PIL import Image

# 步骤1：手动输入图片路径
img_path = r'E:\PythonProject\集成医疗诊断平台\testdata\97a6c59c9eccbecf74e7a91c8a94cf5b_720.png'   # 这里替换成你自己的图片路径
print("你选择的图片：", img_path)

# 步骤2：图片预处理（和训练保持一致）
def preprocess_image(img_path, target_size=(224,224)):
    img = Image.open(img_path).convert('RGB')
    img = img.resize(target_size)
    img_array = np.array(img) / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    return img_array

img_array = preprocess_image(img_path, target_size=(224,224))

# 步骤3：加载模型
model_path = r'../model/best_densenet121_attention.h5'
model = load_model(model_path, compile=False)
print(f"已加载模型：{model_path}")

# 步骤4：类别字典，和你训练时的LabelEncoder顺序一致
index_to_class = {0: 'benign', 1: 'malignant', 2: 'normal'}

# 步骤5：预测
pred = model.predict(img_array)
print("模型输出概率：", pred)
predicted_class_index = np.argmax(pred, axis=1)[0]
predicted_class_name = index_to_class[predicted_class_index]

print(f"\n该图片预测类别为：{predicted_class_name}")

# 可选：输出每一类的概率
for idx, prob in enumerate(pred[0]):
    print(f"类别 {index_to_class[idx]} 概率：{prob:.4f}")